<template>
  <div>
    <!-- 表格顶部菜单 -->
    <TableHeader
      :buttons="['refreshistory', 'comSearch', 'columnDisplay', 'export']"
      :quick-search-placeholder="placeholder"
      @action="baTable.onTableHeaderAction"
    />
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table ref="tableRef" @action="baTable.onTableAction" />
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, provide, onBeforeUnmount, markRaw, inject } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, historyTimeFilter } from "@/utils/common"; // 导入表格api方法生成器
import { EquipMonitorHistory } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import type { TableColumn, TableRow, OptButton } from "@/utils/baTable"; //表格列行类型
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useBackendMonitor } from "@/store/backend/EquipM/monitor"; //实时设备监控仓库
import { useRoute } from "vue-router";
import DateTime from "@/components/DateTime/index.vue";
import _ from "lodash";

// import MQTT from "@/utils/mqtt";
// import type { MqttClient, OnMessageCallback } from "mqtt";
// import Detail from "./detail.vue";

const tableRef = ref();
const route = useRoute();
const placeholder = ref<string>("模糊搜索");
const { proxy } = useCurrentInstance();
const monitor = useBackendMonitor();
const navTabs = inject("navTabs") as any;

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};

// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + EquipMonitorHistory)
      ? (navTabs as any).pageSizeMap.get(route.path + EquipMonitorHistory)
      : 10;
  }
  return 10;
};
//历史记录页数记忆功能
const pageSizeKeepOfHistory = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + EquipMonitorHistory)
      ? (navTabs as any).pageSizeMap.get(route.path + EquipMonitorHistory)
      : false;
  }
  return false;
};

const baTable = new baTableClass(new baTableApi(EquipMonitorHistory), {
  column: [
    { type: "selection", align: "center", operator: false },
    {
      show: filedShowOff("eid"),
      label: "网关编号",
      prop: "eid",
      align: "center",
    },
    // { label: "设备编号", prop: "ecode", align: "center", operator: false },
    {
      show: filedShowOff("thisTime"),
      label: "当前运行时长(时)",
      prop: "thisTime",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + (value / 3600).toFixed(2) + "</p>";
      },
    },
    {
      show: filedShowOff("operating"),
      label: "环保设备运行状态",
      prop: "operating",
      align: "center",
      render: "tag",
      sortable: "custom",
      custom: { "0": "info", "1": "success", "2": "danger" },
      replaceValue: {
        "0": "未运行",
        "1": "运行",
        "2": "未知",
      },
    },
    {
      show: filedShowOff("production"),
      label: "生产设备运行状态",
      prop: "production",
      align: "center",
      render: "tag",
      sortable: "custom",
      custom: { "0": "info", "1": "success", "2": "danger" },
      replaceValue: {
        "0": "未运行",
        "1": "运行",
        "2": "未知",
      },
    },
    {
      show: filedShowOff("flow"),
      label: "风速流量",
      prop: "flow",
      align: "center",
      sortable: "custom",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " m/s" + "</p>";
      },
    },
    {
      show: filedShowOff("temperature"),
      label: "温度",
      prop: "temperature",
      align: "center",
      operator: false,
      render: "customTemplate",
      sortable: "custom",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " &#8451" + "</p>";
      },
    },
    {
      show: filedShowOff("pa"),
      label: "压强",
      prop: "pa",
      align: "center",
      sortable: "custom",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " pa" + "</p>";
      },
    },
    // {
    //   label: "压强",
    //   prop: "pa",
    //   align: "center",
    //   operator: false,
    //   render: "customTemplate",
    //   customTemplate: (row: TableRow, field: TableColumn, value: any) => {
    //     return "<p>" + value + " pa" + "</p>";
    //   },
    // },
    {
      show: filedShowOff("current"),
      label: "电流",
      prop: "current",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " A" + "</p>";
      },
    },
    {
      show: filedShowOff("voltage"),
      label: "电压",
      prop: "voltage",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " V" + "</p>";
      },
    },
    {
      show: filedShowOff("hz"),
      label: "电频",
      prop: "hz",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " Hz" + "</p>";
      },
    },
    {
      show: filedShowOff("runningTime"),
      label: "累计运行时长(时)",
      prop: "runningTime",
      align: "center",
      render: "customTemplate",
      operator: false,
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + (value / 3600).toFixed(2) + "</p>";
      },
    },
    {
      show: filedShowOff("createTime"),
      label: "采集时间",
      prop: "createTime",
      render: "datetime",
      operator: "RANGE",
      // comSearchRender: "customRender",
      // comSearchCustomRender: markRaw(DateTime),
    },
  ],
  filter: { eid: route.query.eid, pageSize: pageSizeKeep() },
  acceptQuery: false, //不接受url的query参数并自动触发通用搜索
});

onMounted(() => {
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //开始连接mqtt
  // startMqtt('主题topic', (topic, message) => {
  //     const msg = JSON.parse(message.toString());
  //     console.log(msg);
  // });
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getHistory(EquipMonitorHistory, "EquipMonitorHistory");
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
});

proxy.eventBus.on("pagesize", (res: any) => {
  console.log("pagesize", route.query);
  baTable.table.loading = true;
  // monitor.pageSize = res.pageSize;
  monitor.pageSize = pageSizeKeepOfHistory()
    ? pageSizeKeepOfHistory()
    : res.pageSize;
  historyTimeFilter(baTable.comSearch.form);
  console.log("historyTimeFilter");

  monitor
    .getHistoryPageMore({ ...monitor.historyFilter, ...res })
    .then((res: any) => {
      baTable.table.data = res.rows;
      baTable.table.total = res.total;
      baTable.table.loading = false;
    });
});
proxy.eventBus.on("pageNum", (res: any) => {
  console.log("pageNum", route.query);
  baTable.table.loading = true;
  monitor.pageNum = res.pageNum;
  monitor
    .getHistoryPageMore({ ...monitor.historyFilter, ...res })
    .then((res: any) => {
      baTable.table.data = res.rows;
      baTable.table.total = res.total;
      baTable.table.loading = false;
    });
});

proxy.eventBus.on("history", (res: any) => {
  console.log("history", res, monitor.historyFilter);
  baTable.table.loading = true;
  let exist = isExist(monitor.historyFilter);
  monitor.getHistoryPageMore({ ...exist, ...res }).then((res: any) => {
    baTable.table.data = res.rows;
    baTable.table.total = res.total;
    baTable.table.loading = false;
  });
});
//判断属性个数
const isEmpty = (obj: anyObj): number => {
  let count = 0;
  if (Object.getOwnPropertyNames) {
    count = Object.getOwnPropertyNames(obj).length;
  } else {
    // 兼容IE
    for (let item in obj) {
      count++;
    }
  }
  return count;
};
//判断页数页面与排序属性是否存在
const isExist = (data: anyObj) => {
  let newData = _.cloneDeep(data);
  newData.operating = "";
  newData.production = "";
  return newData;
};

proxy.eventBus.on("sorthistory", (res: any) => {
  // let newOrder: string | undefined;
  // if (res.prop && res.order) {
  //   newOrder = res.prop + "," + res.order;
  // }
  baTable.table.loading = true;
  monitor.getSortData({ ...monitor.historyFilter, ...res }).then((res: any) => {
    baTable.table.data = res.rows;
    baTable.table.total = res.total;
    baTable.table.loading = false;
  });
});

onBeforeUnmount(() => {
  monitor.pageNum = 1;
  monitor.pageSize = pageSizeKeep();
  proxy.eventBus.off("pageNum"); //移除监听切换页数
  proxy.eventBus.off("pagesize"); //移除监听切换每页个数
  proxy.eventBus.off("sorthistory"); //移除监听排序
});
// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
</script>
<style lang="scss">
.table-com-search {
  .pl-20 {
    margin-left: 50px;
  }
}
</style>
